<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/1
 * Time: 11:36
 */

namespace App\Admin\Extensions\Form;


use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Field\MultipleFile;
use App\Model\Upload;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class UploadMultipleFile extends MultipleFile
{
    protected $dataType = 'string';
    protected $classid;
    protected $deleteUrl = '';
    protected $useUniqueName = true;
    protected $view = 'admin::form.multiplefile';
    public function __construct($column, $arguments = [])
    {
        parent::__construct($column, $arguments);
        $this->classid = 'a'.rand();
        $this->addElementClass($this->classid); //解决hasmany图片覆盖问题
//        $this->deleteUrl = url('admin/upload?id='.$this->original);
    }

    public function setDataType($type){
        $this->dataType = $type;
        return $this;
    }

    public function showzoom()
    {
        $this->fileActionSettings['showZoom'] = true;

        return $this;
    }

    public function setDeleteUrl($url){
        if ($url instanceof \Closure) {
            $this->deleteUrl = $url;
        }else{
            $this->deleteUrl = $url;
        }
        return $this;
    }

    /*public function original()
    {

        if (empty($this->original)) {
            return [];
        }
        if(!is_array($this->original)){
            $this->original = Upload::query()->whereIn('id',explode(',', $this->original))->get()->pluck('fullname')->toArray();
        }else{
            $this->original = array_column($this->original,'fullname');
        }
        dd($this->original);

        return $this->original;
    }*/
    public function prepare($files)
    {

        if (request()->has(static::FILE_DELETE_FLAG)) {
            if ($this->pathColumn) {
                return $this->destroyFromHasMany(request(static::FILE_DELETE_FLAG));
            }

            return $this->destroy(request(static::FILE_DELETE_FLAG));
        }

        if (is_string($files) && request()->has(static::FILE_SORT_FLAG)) {
            return $this->sortFiles($files);
        }

        $targets = array_map([$this, 'prepareForeach'], $files);

        // for create or update
        if ($this->pathColumn) {
            $targets = array_map(function ($target) {
                return [$this->pathColumn => $target];
            }, $targets);
        }
        $ids = [];
        foreach ($targets as $path){
            $p = \Storage::path($path);
            $data = [
                'disk'=>config('admin.upload.disk'),
                'filename'=>basename($path),
                'path'=>dirname($path),
                'fullname'=>$path,
                'mimetype'=>mime_content_type($p),
                'filesize'=>filesize($p),
                'user_id'=>Admin::user()->id,
            ];
            $upload = Upload::query()->firstOrCreate($data);
//            $upload->fill($data);
            $upload->save();
            $ids[] = $upload->id;
        }
        return array_merge(array_filter($this->original()), $ids);
    }

    public function render()
    {
        $value = $this->value();

//        $newValue = Upload::where('id',$value)->value('path');
        if($value){

//            $this->deleteUrl = url('admin/upload?id='.implode(',',$ids));
            $newValue = Upload::query()->whereIn('id',$value)->get()->map(function($item){
                return \Storage::disk($item['disk'])->url($item['fullname']);
            })->toArray();
            if($newValue){
                $this->value($newValue);
            }else{
                $this->value([]);
            }
        }
        if($this->deleteUrl){
            if($this->deleteUrl instanceof \Closure){
                $this->deleteUrl = call_user_func($this->deleteUrl, $this->data, $this);
            }
            $this->options = [
               'deleteUrl'=>$this->deleteUrl
           ];
        }
        /*$this->options = [
            'deleteUrl'=>$this->deleteUrl,
            'deleteExtraData'=>[
////                $this->column => static::FILE_DELETE_FLAG,
//                $this->column => $this->,
                $this->formatName($this->column) => static::FILE_DELETE_FLAG,
                static::FILE_DELETE_FLAG         => '',
                'field'                          => $this->formatName($this->column),
                'ids'                            => $ids,
                '_method'                        => 'DELETE',
            ]
        ];*/
        //修复图片readonly时，图片不能预览的问题
        $zoomAble = <<<EOT
    $(function(){
        $(".kv-file-zoom").attr('disabled',false);
    });
EOT;
        Admin::script($zoomAble);
        return parent::render();
    }
    protected function uploadAndDeleteOriginal(UploadedFile $file)
    {
        $this->renameIfExists($file);

        $path = null;

        if (!is_null($this->storagePermission)) {
            $path = $this->storage->putFileAs($this->getDirectory(), $file, $this->name, $this->storagePermission);
        } else {
            $path = $this->storage->putFileAs($this->getDirectory(), $file, $this->name);
        }

//        $this->destroy();

        return $path;
    }


    public function destroy($key)
    {
        $files = $this->original ?: [];

        $path = Arr::get($files, $key);

        if (!$this->retainable) {
            Upload::query()->find($path)->delete();
        }

        unset($files[$key]);

        return $files;
    }
}
